package com.lzy.mall.seckill.scheduled;

import com.lzy.mall.seckill.service.SeckillService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 秒杀商品定时上线
 * 每天网上3点：上架最近三天需要秒杀的商品。
 * 当天00:00:00 - 23:59:59
 * 明天00:00:00 - 23:59:59
 * 后天00:00:00 - 23:59:59
 * @author lzy
 * @date 2021/10/14 13:59
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class SeckillSkuScheduled {

    private final SeckillService seckillService;

    private final RedissonClient redissonClient;

    private final String update_lock = "seckill:update:lock";

    @Scheduled(cron ="0 * * * * ?")
    public void uploadSeckillSkuLatest(){
        RLock lock = redissonClient.getLock(update_lock);
        lock.lock(30, TimeUnit.SECONDS);
        try {
            System.out.println("秒杀商品定时上架");
            seckillService.uploadSecKillSkuLatest();
        } catch (Exception exception) {
            lock.unlock();
        }
    }

    //TODO 秒杀时间过后缓存处理
}
